package com.chaos.springdemo.core.convert;

import java.util.Collections;
import java.util.Set;

import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.ConditionalGenericConverter;

public class PetGenericConverter implements ConditionalGenericConverter {
    private final Set<ConvertiblePair> set;

    public PetGenericConverter() {
        set = Collections.singleton(new ConvertiblePair(Dog.class, Cat.class));
    }

    @Override
    public boolean matches(TypeDescriptor typeDescriptor, TypeDescriptor typeDescriptor1) {
        return typeDescriptor.getObjectType().isAssignableFrom(Dog.class) &&
                typeDescriptor1.getObjectType().isAssignableFrom(Cat.class);
    }

    @Override
    public Set<ConvertiblePair> getConvertibleTypes() {
        return set;
    }

    @Override
    public Object convert(Object o, TypeDescriptor typeDescriptor, TypeDescriptor typeDescriptor1) {
        Dog dog = (Dog)o;
        Cat cat = new Cat();
        cat.setName(dog.getName());
        cat.setType(dog.getType());
        return cat;
    }
}
